﻿using IGeekFan.AspNetCore.Knife4jUI;
using Microsoft.AspNetCore.Builder;
using Swashbuckle.AspNetCore.SwaggerUI;

namespace _4_NovaAdmin.Web.Core.Middlewares;

public static class SwaggerMiddleware
{
    public static void UseSwagger(this IApplicationBuilder app, IConfiguration Configuration)
    {
        if (app == null) throw new ArgumentNullException(nameof(app));
        // 使用 Swagger
        Microsoft.AspNetCore.Builder.SwaggerBuilderExtensions.UseSwagger(app);
        // 配置 API 文档 UI
        app.UseApiDocumentUI(Configuration);
    }

    public static void UseApiDocumentUI(this IApplicationBuilder app, IConfiguration configuration)
    {
        var swaggerSettings = configuration.GetSection("SwaggerSettings").Get<SwaggerOptions>();

        Action<SwaggerUIOptions> swagger = c =>
        {
            var assembly = Assembly.Load("1`NovaAdmin.Web.Entry");
            // 打印所有资源名称（带大小写）
            var resources = assembly.GetManifestResourceNames();
            Console.WriteLine("可用资源列表：");
            Console.WriteLine(string.Join("\n", resources));
            var targetName = "1`NovaAdmin.Web.Entry.index.html";
            var exists = resources.Any(r => string.Equals(r, targetName, StringComparison.Ordinal));
            Console.WriteLine($"精确匹配结果: {exists}"); // 输出应为 True

            c.IndexStream = () => Assembly.Load("1`NovaAdmin.Web.Entry").GetManifestResourceStream("_1_NovaAdmin.Web.Entry.index.html");
            c.SwaggerEndpoint("/v1/api-docs", "V1 Docs");
            c.RoutePrefix = "";
            c.DocumentTitle = "NovaAdmin API Docs";
        };

        Action<Knife4UIOptions> knife4 = c =>
        {
            c.RoutePrefix = "";
            c.SwaggerEndpoint("/v1/api-docs", "V1 Docs");
            c.DocumentTitle = "NovaAdmin API Docs";
        };

        if (swaggerSettings.UseKnife4UI)
        {
            app.UseKnife4UI(knife4);
        }
        else
        {
            app.UseSwaggerUI(swagger);
        }
    }
}
